package cn.itcast.sms.action;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.constants.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.crm.domain.Customer;
import cn.itcast.sms.utils.BaseAction;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.ws.rs.core.MediaType;

import static com.opensymphony.xwork2.Action.SUCCESS;

@Namespace("/")
@ParentPackage("json-default")
@Scope("protoType")
@Controller
public class OrderAction extends BaseAction<Order> {
    private String sendAreaInfo;//发件人省市区信息
    private String recAreaInfo;//收件人省市区信息

    public void setSendAreaInfo(String sendAreaInfo) {
        this.sendAreaInfo = sendAreaInfo;
    }

    public void setRecAreaInfo(String recAreaInfo) {
        this.recAreaInfo = recAreaInfo;
    }
    @Action(value = "order_add",results = {@Result(name="success",type = "redirect",location = "index.html"),
            @Result(name="login",type="redirect",location="login.html")})
    public String saveOrder(){
        //手动封装省市区
        String[] sendAreaInfoData = sendAreaInfo.split("/");
        Area sendArea =new Area();
        sendArea.setProvince(sendAreaInfoData[0]);
        sendArea.setCity(sendAreaInfoData[1]);
        sendArea.setDistrict(sendAreaInfoData[2]);
        //将发货地址设置到订单中
        model.setSendArea(sendArea);
        String[] recAreaInfoData = recAreaInfo.split("/");
        Area recArea = new Area();
        recArea.setProvince(recAreaInfoData[0]);
        recArea.setCity(recAreaInfoData[1]);
        recArea.setDistrict(recAreaInfoData[2]);
        model.setRecArea(recArea);
        //从session中获取登陆的客户信息,如果没有,返回登陆页面
        Customer customer = (Customer) ServletActionContext.getRequest().getSession().getAttribute("customer");
        if(customer == null){
            return "login";
        }
        //将客户Id设置到order中
        model.setCustomer_id(customer.getId());
        //使用webservice 将数据发送到bos_management中
        WebClient.create(Constants.BOS_MANAGEMENT_URL+"/bos_management/service/orderService/saveOrder").type(MediaType.APPLICATION_JSON).post(model);

        return SUCCESS;
    }
}
